#! /usr/bin/env python
# encoding: utf-8

"""I/O file operations.
"""

from contextlib import contextmanager

@contextmanager
def safe_open(name, mode='r'):
    """Safe open: contextmanager that opens a file and raises the
    exception if there's one.

    It yields the file descriptor with None if all gone right, or
    None with the exception if there was an exception.
    """

    try:
        fd = open(name, mode)
    except IOError as ex:
        yield(None, ex)
    else:
        try:
            yield(fd, None)
        finally:
            fd.close()
